const http=require("http");
const fs=require("fs");
const path=require("path");
const {URL}=require("url");
const { format } = require("path");

function myRouter(myUrl,res){
    if(myUrl.pathname=="/"){
        readPage(res)
    }
    else if(myUrl.pathname.indexOf(".png")!=-1||myUrl.pathname.indexOf(".jpg")!=-1){
        readImage(res)
    }
    else if(myUrl.pathname=="/getlist"){
        sendData(res)
    }
}

function readPage(res){
    let filePath=path.join(__dirname,"index.html");
    let fileContent=fs.readFileSync(filePath);
    res.writeHead(200,{"Content-Type":"text/html"});
    res.end(fileContent);
}


function readImage(res){
    let filePath=path.join(__dirname,"fileDir/icon.png");
    let fileContent=fs.readFileSync(filePath);
    res.writeHead(200,{"Content-Type":"image/png"});
    res.end(fileContent);
}


function formatTime(timer){
    let date1=new Date(timer);
    let year=date1.getFullYear();
    let month=date1.getMonth();
    let day=date1.getDate();
    return year+"-"+month+"-"+day
}

function sendData(res){
    let dataList=[];
    let dirPath=path.join(__dirname,"fileDir");
    let fileList=fs.readdirSync(dirPath);
    for(let i=0;i<fileList.length;i++){
        let childPath=path.join(dirPath,fileList[i])
        let statObj=fs.statSync(childPath);
        let fileObj={};
        fileObj.fileType=statObj.isFile()?"file":"folder"
        fileObj.fileName=fileList[i];
        fileObj.fileSize=statObj.size
        fileObj.fileTime=formatTime(statObj.ctimeMs)
        dataList.push(fileObj)
    }
    dataList=JSON.stringify(dataList)
    res.end(dataList)
}

http.createServer((req,res)=>{ 
    let myUrl=new URL(req.url,"http://192.168.174.166:3000");
    myRouter(myUrl,res)
}).listen(3000);

console.log("server is listening 3000...");